import datetime

import requests
import json
from applications.extensions import db
from applications.models import FundIndexEva
from flask import current_app


class Crawl_Index_Eva(object):
    def __init__(self):
        self.req_url = 'https://danjuanfunds.com/djapi/index_eva/dj'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.39'
        }

    def run(self):
        res_data = requests.get(self.req_url, headers=self.headers)
        fund_items = json.loads(res_data.text)['data']['items']
        today = datetime.date.today()
        for fund_item in fund_items:
            fund_index_eva = FundIndexEva()
            fund_index_eva.index_code = fund_item['index_code']
            fund_index_eva.name = fund_item['name']
            fund_index_eva.ttype = fund_item['ttype']
            fund_index_eva.pe = fund_item['pe']
            fund_index_eva.pb = fund_item['pb']
            fund_index_eva.pe_percentile = fund_item['pe_percentile']
            fund_index_eva.pb_percentile = fund_item['pb_percentile']
            fund_index_eva.roe = fund_item['roe']
            fund_index_eva.yeild = fund_item['yeild']
            fund_index_eva.peg = fund_item['peg'] if 'peg' in fund_item is not None else 0
            fund_index_eva.ts_at = fund_item['ts']
            fund_index_eva.eva_type = fund_item['eva_type']
            fund_index_eva.eva_type_int = fund_item['eva_type_int']
            fund_index_eva.fund_url = fund_item['url']
            fund_index_eva.bond_yeild = fund_item['bond_yeild']
            fund_index_eva.create_date = today
            current_app.logger.info('%s' % fund_index_eva)
            self.save_data(fund_index_eva)

    def save_data(self, fund_index_eva: FundIndexEva):
        db.session.add(fund_index_eva)
        db.session.commit()


if __name__ == '__main__':
    Crawl_Index_Eva().run()
